#!/usr/bin/ruby

require File.dirname(__FILE__) + "/shared.rb"

NOISE_PROFILE = RAMO_HOME + "noise-profile"
NOISE_RED_AMT = 0.3

DEBUG = false 

def main(fname, duration)
    temp_dir = `mktemp -d`[0..-2]
    temp_fname = temp_dir + "/temp-rec.#{TMP_AUD_FORMAT}"

    #duration = 60 * BLOCK_DUR + OVERLAP_DUR - lag
    
#    exec( "rec -c 1 -r #{RATE} #{temp_fname}\
#        trim 0 #{duration.to_f}" )
#        #trim 0 #{BLOCK_DUR}:#{pad2(OVERLAP_DUR)}" )
#    exec( "sox #{temp_fname} #{fname} \
#        silence 1 0 #{THRESHOLD}% -1 #{SILENCE_DUR.to_f} #{THRESHOLD}%" )
    exec( "rec -c 1 -r #{RATE} #{temp_fname}\
        trim 0 #{duration.to_f}  \
        silence -l 1 0 #{THRESHOLD}% -1 #{SILENCE_DUR.to_f} #{THRESHOLD}% \
        noisered #{NOISE_PROFILE} #{NOISE_RED_AMT.to_f} \
        >/dev/null 2>/dev/null" )

    `mv #{temp_fname} #{fname}`
    `rmdir #{temp_dir}` 
end

def exec(cmd)
    if DEBUG
        puts "sh cmd = #{cmd}"
        `#{cmd}`
    else
        `#{cmd}`
    end
end

if __FILE__ == $0
    if ARGV.length() < 1
        puts "Usage: mk-rec filename"
    else
        fname = ARGV[0]
        duration = ARGV[1].to_i.to_f

        if File.exists?(fname)
            puts "File #{fname} already exists - will not overwrite"
            # a precaution for giving the script root permissions
        else
            main(fname, duration)
        end
    end
end
